package com.atguigu.gulimall.auth.component;

import com.atguigu.common.utils.HttpUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : wenchao.long
 * @date : Created in 2021/8/10 11:06 周二
 * @description :
 */
@Component
@Slf4j
@AllArgsConstructor
@EnableConfigurationProperties({WeiboProperties.class, GiteeProperties.class})
public class OauthComponent {

    private final WeiboProperties weiboProperties;

    private final GiteeProperties giteeProperties;

    public HttpResponse weiboOauth(String code) {
        return oauth(weiboProperties.getClientId(), weiboProperties.getClientSecret(), weiboProperties.getGrantType(),
                weiboProperties.getRedirectUri(), weiboProperties.getHost(), weiboProperties.getPath(), code);
    }

    public HttpResponse giteeOauth(String code) {
        return oauth(giteeProperties.getClientId(), giteeProperties.getClientSecret(), giteeProperties.getGrantType(),
                giteeProperties.getRedirectUri(), giteeProperties.getHost(), giteeProperties.getPath(), code);
    }

    private HttpResponse oauth(String clientId, String clientSecret, String grantType, String redirectUri,
                               String host, String path, String code) {
        Map<String, String> querys = new HashMap<>(10);
        Map<String, String> headers = new HashMap<>(10);
        Map<String, String> bodys = new HashMap<>(10);
        bodys.put("client_id", clientId);
        bodys.put("client_secret", clientSecret);
        bodys.put("grant_type", grantType);
        bodys.put("redirect_uri", redirectUri);
        bodys.put("code", code);
        HttpResponse response = null;

        try {
            response = HttpUtils.doPost(host, path, "POST", headers, querys, bodys);
            log.info("响应结果" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}
